<template>
  <div>
    <div class="top-operate-default  mar-b-20">
      <div class="search-item">
        <label>搜索：</label>
        <el-input v-model="memberListQuery.keyword" @keyup.enter.native="handleSearch" placeholder="昵称/手机号/招募员姓名/招募员手机号"
          style="width: 350px"></el-input>
        <label class="mar-l-20">注册时间：</label>
        <el-date-picker v-model="starEndTime" type="datetimerange" unlink-panels range-separator="至"
        value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']"
          start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
        <label class="mar-l-20">主播权限：</label>
        <el-select v-model="memberListQuery.anchorAuthority" placeholder="主播权限" clearable class="pad-l-10"
          style="width: 140px">
          <el-option label="开启" value="1"></el-option>
          <el-option label="关闭" value="0"></el-option>
        </el-select>
        <label class="mar-l-20">等级：</label>
        <el-select v-model="memberListQuery.wholesalerGrade" placeholder="等级" clearable class="pad-l-10"
          style="width: 140px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="handleSearch" style="margin-left: 10px">查询</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </el-button-group>
      </div>
    </div>
    <!-- 操作区域 -->
    <div class="tabs-box mar-t-15">
      <el-tabs type="card" v-model="secondActiveName" class="member-list-tab" @tab-click="handleClick">
        <el-tab-pane :label="allName" name="0"></el-tab-pane>
        <el-tab-pane :label="enterpriseName" name="2"></el-tab-pane>
        <el-tab-pane :label="recruiterName" name="1"></el-tab-pane>
      </el-tabs>
    </div>
    <!-- 全选、操作 -->
    <div>
      <div class="pad-t-15 pad-b-15 font-14 v-align-c">
        <el-checkbox class="mar-l-14 mar-r-0" v-model="allChecked" @change="selectAll"><span
            class="mar-l-20">当页全选</span></el-checkbox>
        <span class="pad-l-4 pad-r-4">|</span>
        <div class="width-80">已选{{multipleSelection.length}}项</div>
        <el-button class="batch-btn mar-r-10" @click="batchCloseAuthority()">关闭批发权限</el-button>
        <el-select v-model="selectedOption" class="inputBox" placeholder="批量设置等级" @change="gradeClick()">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <!-- 内容列表 -->
    <div class="table-container">
      <el-table ref="multipleTable" :data="memberList" @sort-change="sortChange"
        @selection-change="handleSelectionChange" v-loading="listLoading" element-loading-text="加载中" style="width: 100%"
        header-cell-class-name="default-header" row-class-name="default-row">
        <el-table-column width="55px" type="selection"></el-table-column>
        <el-table-column width="260px" label="店主信息" fixed="left">
          <template slot-scope="scope">
            <div @click="handleUpdate(scope.row)" class="flex v-align-c cursor-p">
              <el-tooltip class="item" effect="dark" :content="'微客ID:' + scope.row.memberId" placement="top-start">
                <label><img :src="scope.row.avatar" class="user-avatar cursor-p" v-if="scope.row.avatar"></label>
              </el-tooltip>
              <div class="font-14 pad-l-10">
                <div><span class="font-color-9">昵称：</span>{{scope.row.nickname}}</div>
                <div><span class="font-color-9">手机：</span>{{scope.row.phone}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="260px" label="等级" prop="wholesalerGrade">
          <template slot-scope="scope">
            {{ wholesalerGradeMap[scope.row.wholesalerGrade] ? wholesalerGradeMap[scope.row.wholesalerGrade] : '' }}
          </template>
        </el-table-column>
        <el-table-column width="300px" label="来源">
          <template slot-scope="scope">
            <span v-if="scope.row.nature == 1">
              <span>招募员招募</span>
              <div><span class="font-color-9">姓名：</span>{{scope.row.recruiterName}}</div>
              <div><span class="font-color-9">手机：</span>{{scope.row.recruiterPhone}}</div>
            </span>
            <span v-if="scope.row.nature == 2">总部招募</span>
          </template>
        </el-table-column>
        <el-table-column width="260px" label="注册时间" prop="passDate" sortable="custom">
        </el-table-column>
        <el-table-column width="200px" label="主播权限">
          <template slot-scope="scope">
            <span>{{ scope.row.anchorAuthority == 1 ? '开启' : '关闭' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="200px" label="授信额度">
          <template slot-scope="scope">
            <div class="line-h-14" v-if="scope.row.creditType === 2">
              <div><span class="font-blue"> {{ creditTypeList[scope.row.creditType] }}</span></div>
              <div><span class="font-color-9">最高额度：</span>￥{{scope.row.highestQuota ? scope.row.highestQuota : '0.00'}}
              </div>
              <div><span class="font-color-9">已用额度：</span>￥{{scope.row.usedQuota ? scope.row.usedQuota : '0.00'}}</div>
              <div><span
                  class="font-color-9">剩余额度：</span>￥{{scope.row.highestQuota && scope.row.usedQuota ? scope.row.highestQuota - scope.row.usedQuota : '0.00' }}
              </div>
            </div>
            <div class="line-h-14" v-else-if="scope.row.creditType === 1 || scope.row.creditType === 3">
              <div><span class="font-blue"> {{ creditTypeList[scope.row.creditType] }}</span></div>
            </div>
            <div class="line-h-14" v-else>
              <div><span class="font-red">未选择授信类型</span></div>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="260px" label="累计成交">
          <template slot-scope="scope">
            <div><span class="font-color-9">订单：</span>{{scope.row.orderNum}}</div>
            <div><span class="font-color-9">金额：</span>{{scope.row.orderPrice}}</div>
          </template>
        </el-table-column>
        <el-table-column width="280px" label="备注" prop="remarkName"></el-table-column>
        <el-table-column min-width="200px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="handleUpdate(scope.row)">查看</el-button>
            <el-button type="text" size="medium" @click="doOpenRemark(scope.row)">备注</el-button>
            <el-button type="text" size="medium" @click="setHighestQuotaShow(scope.row)">设置授信额度</el-button>
            <el-button type="text" @click="goApplyDetailMesg(scope.row)">申请详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="memberListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="memberListQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 备注dialog -->
    <el-dialog title="备注" :visible.sync="remarkVisible" width="460px">
      <div style="padding:20px;">
        <el-input type="textarea" :rows="6" placeholder="请输入内容" v-model="memberRemark.remarkName"></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRemark">确认</el-button>
        <el-button @click="remarkVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!--设置授信额度-->
    <el-dialog title="设置授信额度" :visible.sync="setHighestQuotaVisible" :close-on-press-escape="true" width="460px">
      <div style="margin-left: 55px">
        <span style="font-size: 16px">授信类型：</span>
        <el-radio v-model="setHighestQuotaInfo.creditType" label="1" @change="creditTypeChange">即时付款</el-radio>
      </div>
      <div style="margin-left: 140px; margin-top: 10px">
        <el-radio v-model="setHighestQuotaInfo.creditType" label="2" @change="creditTypeChange">额度授信</el-radio>
        <el-input style="width: 250px; margin-top: 10px" placeholder="请输入最高额度"
          v-model="setHighestQuotaInfo.highestQuota" :disabled="highestQuotaShow"
          @keyup.native="setHighestQuotaInfo.highestQuota = checkInputNum(setHighestQuotaInfo.highestQuota)"
          size="mini"><template slot="append">元</template></el-input>
        <div class="config-tip font-12 font-color-9">
          最高额度必须大于等于0,
          <el-tooltip placement="top">
            <div slot="content">
              当前最高额度: ￥{{ setHighestQuotaInfo.highestQuota ? setHighestQuotaInfo.highestQuota : '0.00' }}<br />
              已使用额度: ￥{{ setHighestQuotaInfo.usedQuota ? setHighestQuotaInfo.usedQuota : '0.00' }}<br />
              当前可用额度:
              ￥{{ setHighestQuotaInfo.highestQuota && setHighestQuotaInfo.usedQuota ? setHighestQuotaInfo.highestQuota - setHighestQuotaInfo.usedQuota : '0.00' }}<br />
            </div>
            <i class="el-icon-info">查看当前额度</i>
          </el-tooltip>
        </div>
      </div>
      <div style="margin-left: 140px; margin-top: 10px">
        <el-radio v-model="setHighestQuotaInfo.creditType" label="3" @change="creditTypeChange">不限额度</el-radio>
        <div class="config-tip font-12 font-color-9">选用不限额度可能导致不可控的分销商欠款，谨慎使用！</div>
      </div>
      <div slot="footer" class="dialog-footer pad-t-20">
        <el-button type="primary" @click="setHighestQuotaType">保存</el-button>
        <el-button @click="setHighestQuotaVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 申请详情 弹窗 -->
    <apply-detail ref="applyDetail"></apply-detail>
  </div>
</template>

<script>
  import {
    getNameByPath
  } from '@/utils/get-name-by-path'
  import {
    saveMemberRemark,
    doSetHighestQuota
  } from '@/api/user/member'

  import {
    pagingMemberRoleAuthority,
    statisticsWholesaleRoleAuthorityByNature,
    updateBatchStatus,
    updateBatchWholesalerGrade
  } from '@/api/user/memberRoleAuthority'
  import elDragDialog from '@/directive/el-dragDialog'
  import {
    getDictByGroupName
  } from '@/api/common/common'
  import {
    listWholesalerGrade
  } from '@/api/user/memberGrade'
  import ApplyDetail from '../apply-detail'
  export default {
    name: getNameByPath(),
    directives: {
      elDragDialog
    },
    components: {
      ApplyDetail
    },

    props: {
      recruiterId: {
        type: String
      },
      showFlag: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        selectedOption: '',
        options: [],
        // 日期model
        starEndTime: [],
        memberListQuery: {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          anchorAuthority: '',
          authorityStatus: 1,
          startDate: null,
          endDate: null,
          keyword: '',
          nature: '',
          wholesaleAuthority: '',
          memberRoleType: 1 // 微客角色类型：1-批发商，2-主播
        },
        // 备注表单
        memberRemark: {
          memberRemarkId: '',
          remarkType: 4,
          remarkName: '',
          memberId: '',
          userId: this.getEnterpriseId()
        },
        secondActiveName: '0',
        total: null,
        listLoading: true,
        remarkVisible: false,
        memberList: [],
        multipleSelection: [],
        allName: '全部',
        enterpriseName: '总部招募',
        recruiterName: '招募员招募',
        allChecked: false,
        setHighestQuotaInfo: {
          memberId: '',
          creditType: 1,
          highestQuota: 0,
          usedQuota: 0
        },
        setHighestQuotaVisible: false,
        highestQuotaShow: true,
        creditTypeList: [],
        wholesalerGradeMap: {},
        dateColumn: 'passTime'
      }
    },
    filters: {},
    watch: {
      showFlag(val) {
        if (val) {
          this.initSatisticsWholesaleRoleAuthorityByNature()
          this.initMemberRoleAuthority()
        }
      }
    },
    // 初始化页面
    created() {
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.gradeValue) {
        this.memberListQuery.wholesalerGrade = queryParams.gradeValue
      }
      this.memberListQuery.recruiterId = this.recruiterId
      this.initSatisticsWholesaleRoleAuthorityByNature()
      this.initMemberRoleAuthority()
      this.getWholesalerGradeList()
    },
    mounted() {},
    methods: {
      gradeClick() {
        if (!this.selectedOption) {
          this.$message.error('批量设置等级错误')
          return
        }
        if (this.multipleSelection.length <= 0) {
          this.msgError('请勾选要设置等级的数据')
          this.selectedOption = ''
          return
        }
        var roleAuthorityIds = []
        var memberIds = []
        this.multipleSelection.forEach((item) => {
          roleAuthorityIds.push(item.roleAuthorityId)
        })
        updateBatchWholesalerGrade(this.getEnterpriseId(), roleAuthorityIds, memberIds, this.selectedOption).then(
          response => {
            this.selectedOption = ''
            if (response.isError) return
            this.msgSuccess(response.msg)
            this.initSatisticsWholesaleRoleAuthorityByNature()
            this.initMemberRoleAuthority()
          })
      },
      // 显示申请详情弹窗
      goApplyDetailMesg(item) {
        this.$nextTick(() => {
          this.$refs.applyDetail.setData(item)
          this.$refs.applyDetail.open()
        })
      },
      // 获取批发商等级集合
      getWholesalerGradeList() {
        const enterpriseId = this.getEnterpriseId()
        listWholesalerGrade(enterpriseId).then(response => {
          if (response.isError) return
          const gradeList = response.data
          var gradeMap = {}
          gradeList.forEach(e => {
            this.options.push({
              'value': e.gradeValue,
              'label': e.gradeName
            })
            gradeMap[e.gradeValue] = e.gradeName
          })
          this.wholesalerGradeMap = gradeMap
        })
      },
      // 统计
      initSatisticsWholesaleRoleAuthorityByNature() {
        this.allName = '全部'
        this.enterpriseName = '总部招募'
        this.recruiterName = '招募员招募'
        statisticsWholesaleRoleAuthorityByNature(this.memberListQuery).then(response => {
          if (response.isError) return
          this.allName += '(' + Math.floor(response.data.allNum) + '）'
          this.enterpriseName += '(' + Math.floor(response.data.enterpriseNum) + '）'
          this.recruiterName += '(' + Math.floor(response.data.recruiterNum) + '）'
        })
      },
      // 初始化
      initMemberRoleAuthority() {
        this.listLoading = true
        this.memberListQuery.nature = this.secondActiveName === '0' ? '' : this.secondActiveName
        this.memberListQuery.dateColumn = this.dateColumn
        this.memberListQuery.startDate = (this.starEndTime && this.starEndTime.length > 0) ? this.starEndTime[0] : null
        this.memberListQuery.endDate = (this.starEndTime && this.starEndTime.length > 0) ? this.starEndTime[1] : null
        pagingMemberRoleAuthority(this.memberListQuery).then(response => {
          if (response.isError) return
          this.memberList = response.data.records
          this.total = response.data.total
          this.listLoading = false
          getDictByGroupName('MemberDTO.creditType').then(response => {
            this.creditTypeList = response.data.creditType
          })
        })
      },
      // 列表排序
      sortChange(data) {
        const {
          prop,
          order
        } = data
        if (prop === 'registeredTime') {
          if (order === 'ascending') {
            this.memberListQuery.asc = 'registeredTime'
            this.memberListQuery.desc = ''
          } else {
            this.memberListQuery.asc = ''
            this.memberListQuery.desc = 'registeredTime'
          }
        }
        this.initMemberRoleAuthority()
      },
      // tab切换事件
      handleClick() {
        this.memberListQuery.currentPage = 1
        this.initMemberRoleAuthority()
      },
      // 查询事件
      handleSearch() {
        this.memberListQuery.currentPage = 1
        this.initSatisticsWholesaleRoleAuthorityByNature()
        this.initMemberRoleAuthority()
      },
      // 重置
      resetSearch() {
        this.starEndTime = []
        this.memberListQuery = {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId(),
          anchorAuthority: '',
          authorityStatus: 1,
          startDate: null,
          endDate: null,
          keyword: '',
          nature: '',
          wholesaleAuthority: '',
          memberRoleType: 1 // 微客角色类型：1-批发商，2-主播
        }
        this.initSatisticsWholesaleRoleAuthorityByNature()
        this.initMemberRoleAuthority()
      },
      // 批量关闭权限
      batchCloseAuthority() {
        if (this.multipleSelection.length <= 0) {
          this.$message.error('请选择要操作的数据')
          return
        }
        var memberIds = []
        var roleAuthorityIds = []
        // var memberAuthorityList = []
        this.multipleSelection.forEach((item) => {
          // var memberAuthority = {
          //   memberId: item.memberId,
          //   enterpriseId: this.getEnterpriseId(),
          //   wholesaleAuthority: 0
          // }
          // memberAuthorityList.push(memberAuthority)
          memberIds.push(item.memberId)
        })
        var status = 2
        var rejectReason = '手动关闭批发权限'
        this.$confirm('是否确认关闭批发权限？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          updateBatchStatus(this.getEnterpriseId(), this.memberListQuery.memberRoleType, roleAuthorityIds,
            memberIds, status, null, rejectReason).then(response => {
            if (response.isError) return
            this.initSatisticsWholesaleRoleAuthorityByNature()
            this.initMemberRoleAuthority()
            this.$message({
              type: 'success',
              message: '关闭权限成功'
            })
          })
        })
      },
      // 打开备注dialog事件
      doOpenRemark(row) {
        this.memberRemark.memberRemarkId = row.memberRemarkId
        this.memberRemark.memberId = row.memberId
        this.memberRemark.remarkName = row.remarkName
        this.memberRemark.userId = this.getEnterpriseId()
        this.remarkVisible = true
      },
      // 备注确定事件
      submitRemark() {
        saveMemberRemark(this.memberRemark).then(response => {
          if (response.isError) return
          this.$message({
            message: '保存成功',
            type: 'success'
          })
          this.remarkVisible = false
          this.initMemberRoleAuthority()
        })
      },
      // 详情
      handleUpdate(row) {
        this.$router.push({
          path: '/user/member-wholesale/details/index',
          query: {
            memberId: row.memberId,
            enterpriseId: this.getEnterpriseId()
          }
        })
      },
      handleSizeChange(val) {
        this.memberListQuery.size = val
        this.initMemberRoleAuthority()
      },
      handleCurrentChange(val) {
        this.memberListQuery.currentPage = val
        this.initMemberRoleAuthority()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (this.multipleSelection.length === this.memberList.length) {
          this.allChecked = true
        } else {
          this.allChecked = false
        }
      },
      // 全选事件
      selectAll() {
        if (this.multipleSelection.length === 0 || this.multipleSelection.length < this.memberList.length) {
          this.memberList.forEach(item => {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 打开设置授信额度窗口
      setHighestQuotaShow(row) {
        this.setHighestQuotaInfo.memberId = row.memberId
        this.setHighestQuotaInfo.creditType = row.creditType ? row.creditType.toString() : '1'
        this.setHighestQuotaInfo.highestQuota = row.highestQuota ? row.highestQuota : '0'
        this.setHighestQuotaInfo.usedQuota = row.usedQuota ? row.usedQuota : '0'
        this.highestQuotaShow = this.setHighestQuotaInfo.creditType === '1' || this.setHighestQuotaInfo.creditType ===
          '3'
        this.setHighestQuotaVisible = true
      },
      creditTypeChange() {
        // 授信类型 1- 即时付款 2- 额度授信 3- 不限额度
        if (this.setHighestQuotaInfo.creditType === '1' || this.setHighestQuotaInfo.creditType === '3') {
          this.highestQuotaShow = true
        } else {
          this.highestQuotaShow = false
        }
      },
      setHighestQuotaType() {
        if (this.setHighestQuotaInfo.creditType === '1') {
          this.saveHighestQuotaInfo()
          return
        }
        // 如果选择2- 额度授信,要检查highestQuota>0 新的最高额度不能低于已使用额度，请重新设置。
        if (this.setHighestQuotaInfo.creditType === '2') {
          if (!this.setHighestQuotaInfo.highestQuota) {
            this.$message.error('选择额度授信,需输入最高额度')
            return
          }
          if (Number(this.setHighestQuotaInfo.highestQuota) < Number(this.setHighestQuotaInfo.usedQuota)) {
            this.$message.error('最高额度需大于已使用额度(' + this.setHighestQuotaInfo.usedQuota + ')元')
            return
          }
          this.saveHighestQuotaInfo()
          return
        }
        // 如果选择3- 不限额度 弹出二次确认框 选用“不限额度”授信类型，可能导致不可控的分销商欠款，确定继续选用？  继续选用 取消
        if (this.setHighestQuotaInfo.creditType === '3') {
          this.$confirm('选用“不限额度”授信类型，可能导致不可控的分销商欠款，确定继续选用？', '提示', {
            confirmButtonText: '继续选用',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveHighestQuotaInfo()
          }).catch(() => {})
          return
        }
      },
      // 保存额度授信配置
      saveHighestQuotaInfo() {
        doSetHighestQuota(this.setHighestQuotaInfo).then(response => {
          if (response.isError) return
          this.initMemberRoleAuthority()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          setTimeout(() => {
            this.setHighestQuotaVisible = false
          }, 20)
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 59px;
    height: 59px;
    display: block;
    border-radius: 50%;
  }

  .inputBox {
    display: flex;

    .el-input__inner {
      background-color: #dad8d8;
    }

    ::placeholder {
      //通过这个设置
      color: #606266;
    }
  }
</style>
